//
//  ICComEmpListViewController.m
//  ICome
//
//  Created by zhang_rongwu on 16/3/7.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICComEmpListViewController.h"
#import "ICComEmpListTableViewCell.h"
#import "ICMessageDatabase.h"
#import "ICDetailSearchController.h"

@interface ICComEmpListViewController()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate, DetailSearchDelegate, ICComEmpListTableViewCellDelegate>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataList;
@property (nonatomic, strong)ICDetailSearchController *searchVC;
@property (nonatomic, strong)ICBaseSearchViewController *searchController;
@property (nonatomic, strong) UIButton *rightBtn;
@end

@implementation ICComEmpListViewController

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setNav];
    [self getData];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55.0f * Level;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *res = @"ICComEmpListTableViewCell";
    ICComEmpListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:res];
    if (!cell) {
        cell = [[ICComEmpListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:res];
    }
    cell.model = [self.dataList objectAtIndex:indexPath.row];
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ICEmpInfoModel *model = [self.dataList objectAtIndex:indexPath.row];
    model.select = !model.select;
    NSInteger datacount = 0;
    for (ICEmpInfoModel *disable in self.dataList) {
        if(disable.select){
            datacount++;
        }
    }
    if(datacount> 0){
//        self.navigationItem.rightBarButtonItem.enabled = YES;
//        NSDictionary *dic = [NSDictionary dictionaryWithObject:DEFAULT_SUBJECT_COLOR forKey:NSForegroundColorAttributeName];
//        [self.navigationItem.rightBarButtonItem setTitleTextAttributes:dic forState:UIControlStateNormal];
        self.rightBtn.enabled = YES;
        self.rightBtn.hidden = NO;
        [self.rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }else{
//        self.navigationItem.rightBarButtonItem.enabled = NO;
//        NSDictionary *dic = [NSDictionary dictionaryWithObject:ICRGB(0xd5d5d5) forKey:NSForegroundColorAttributeName];
//        [self.navigationItem.rightBarButtonItem setTitleTextAttributes:dic forState:UIControlStateNormal];
        self.rightBtn.enabled = NO;
        self.rightBtn.hidden = YES;
        [self.rightBtn setTitleColor:[UIColor colorWithHexString:@"#B0B0B0"] forState:UIControlStateNormal];
    }
    [self.tableView reloadData];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES];
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:ICSEARCHCANCELCOLOR forState:UIControlStateNormal];
        }
    }
}

#pragma mark - CustomDelegate
- (void)detailSearch:(NSString *)eId {
    for (int index = 0; index < self.dataList.count; index++) {
        ICEmpInfoModel *_model = [self.dataList objectAtIndex:index];
        if ([_model.eId isEqualToString:eId]) {
            NSIndexPath *_indexPath = [NSIndexPath indexPathForRow:index inSection:0];
            [self tableView:self.tableView didSelectRowAtIndexPath:_indexPath];
        }
    }
    
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}

- (void)emp_clickSlectButtonInCell:(ICComEmpListTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
}
#pragma mark - event response
- (void)deleteBtnClicked {
    [MBProgressHUD showMessage:@"正在删除..." toView:self.view];
    
    NSMutableArray* deleteList = [[NSMutableArray alloc] init];
    for (ICEmpInfoModel *model in self.dataList) {
        if (model.select) {
            [deleteList addObject:model.eId];
            
        }
    }
     NSString *gId = self.gId == nil ? @"": self.gId;
    NSDictionary *param = @{@"gId":gId,
                            @"eIds":deleteList};
    [[ICSocketRequestManager sharedInstance] kickGroupUserArrayWithObject:param Success:^(id response) {
        [MBProgressHUD hideHUDForView:self.view];
        // 删除关联表
        for(NSString * eId in deleteList){
        [ICMessageDatabase deleteGroupUserWithGroupId:self.gId eId:eId];
        }
        if ([self.delegate respondsToSelector:@selector(deleteSuccess)]) {
            [self.delegate deleteSuccess];
        }
        [self.navigationController popViewControllerAnimated:YES];
    } Failure:^(NSError *error, id other) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:error.domain];
    }];
    
//    [MBProgressHUD showMessage:@"正在删除..." toView:self.view];
//    for (ICEmpInfoModel *model in self.dataList) {
//        if (model.select) {
//            NSString *gId = self.gId == nil ? @"": self.gId;
//            NSDictionary *param = @{@"gId":gId,
//                                    @"eId":model.eId};
//            [[ICSocketRequestManager sharedInstance] kickGroupUserWithObject:param Success:^(id response) {
//                [MBProgressHUD hideHUDForView:self.view];
//                // 删除关联表
//                [ICMessageDatabase deleteGroupUserWithGroupId:self.gId eId:model.eId];
//                if ([self.delegate respondsToSelector:@selector(deleteSuccess)]) {
//                    [self.delegate deleteSuccess];
//                }
//                [self.navigationController popViewControllerAnimated:YES];
//            } Failure:^(NSError *error, id other) {
//                [MBProgressHUD hideHUDForView:self.view];
//                [MBProgressHUD showError:error.domain];
//            }];
//        }
//    }

}
#pragma mark - private methods
// 设置页面布局
- (void)setUI {
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
}
// 设置navigation
- (void)setNav {
    self.title = @"删除成员";
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.enabled = NO;
    _rightBtn.frame = CGRectMake(0, 0, 44., 44.);
    [_rightBtn setTitle:@"删除" forState:UIControlStateNormal];
    [_rightBtn setTitleColor:[UIColor colorWithHexString:@"#B0B0B0"] forState:UIControlStateNormal];
    _rightBtn.hidden = YES;

    [_rightBtn addTarget:self action:@selector(deleteBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    _rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    _rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
    
//    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(deleteBtnClicked)]];
//    self.navigationItem.rightBarButtonItem.enabled = NO;
//    NSDictionary *dic = [NSDictionary dictionaryWithObject:ICRGB(0xd5d5d5) forKey:NSForegroundColorAttributeName];
//    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:dic forState:UIControlStateNormal];
}

// 网络请求
- (void)getData {
    for (ICUser *user in self.users) {
        ICEmpInfoModel *model = [[ICEmpInfoModel alloc] init];
        model.eId = user.eId;
        model.eName = user.eName;
        model.photoId = user.photoId;
        if (![user.eId isEqualToString:[ICUser currentUser].eId]) { // 把自己省略
            [self.dataList addObject:model];
        }
    }
    [self.tableView reloadData];

}

#pragma mark - getters and setters
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height - 29) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.userInteractionEnabled = YES;
        _tableView.backgroundColor = BACKGROUNDCOLOR;
        self.tableView.tableHeaderView = self.searchController.searchBar;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

-(NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [[NSMutableArray alloc] init];
    }
    return _dataList;
}



- (ICBaseSearchViewController *) searchController {
    if (!_searchController) {
        
        _searchController = [[ICBaseSearchViewController alloc] initWithSearchResultsController:self.searchVC];
        _searchController.placeholder = @"搜索";
        _searchController.searchBar.delegate  = self;
        _searchController.searchResultsUpdater = self.searchVC;
        // 覆盖视图控制器的视图窗口的部分决定了呈现视图控制器的视图的大小。默认值是NO。
        self.definesPresentationContext = YES;
        
    }
    return _searchController;
}

- (ICDetailSearchController *) searchVC {
    if (!_searchVC) {
        _searchVC = [[ICDetailSearchController alloc] init];
        _searchVC.delegate = self;
        _searchVC.gId = self.gId;
    }
    return _searchVC;
}

@end
